//
//  LTDownloadItem.m
//  Total
//
//  Created by xin on 2017/7/28.
//  Copyright © 2017年 elephants. All rights reserved.
//

#import "LTDownloadItem.h"

@interface LTDownloadItem()

@property (nonatomic, strong, readwrite, nonnull) NSString *downloadToken;
@property (nonatomic, strong, readwrite, nullable) NSURLSessionDownloadTask * sessionDownloadTask;
@property (nonatomic, strong, readwrite, nonnull) NSProgress *progress;

@end

@implementation LTDownloadItem

- (nullable instancetype)initWithDownloadToken:(nonnull NSString *)downloadToken sessionDownloadTask:(nullable NSURLSessionDownloadTask *)aSessionDownloadTask
{
    self = [super init];
    if (self) {
        self.downloadToken = downloadToken;
        self.sessionDownloadTask = aSessionDownloadTask;
        
        self.receivedFileSizeInBytes = 0.;
        self.expectedFileSizeInBytes = 0.;
        self.resumedFileSizeInBytes = 0.;
        self.bytesPerSecondSpeed = 0;
        self.lastHttpStatusCode = 0;
        
        self.progress = [[NSProgress alloc] initWithParent:[NSProgress currentProgress] userInfo:nil];
        self.progress.kind = NSProgressKindFile;
        [self.progress setUserInfoObject:NSProgressFileOperationKindKey forKey:NSProgressFileOperationKindDownloading];
        [self.progress setUserInfoObject:downloadToken forKey:@"downloadToken"];
        self.progress.cancellable = YES;
        self.progress.pausable = NO;
        self.progress.totalUnitCount = NSURLSessionTransferSizeUnknown;
        self.progress.completedUnitCount = 0;
    }
    return self;
}

- (void)setReceivedFileSizeInBytes:(int64_t)receivedFileSizeInBytes
{
    _receivedFileSizeInBytes = receivedFileSizeInBytes;
    
    if (receivedFileSizeInBytes> 0) {
        if ((self.expectedFileSizeInBytes > 0)) {
            self.progress.completedUnitCount = receivedFileSizeInBytes;
        }
    }
}

#pragma mark - Description

- (NSString *)description
{
    NSMutableDictionary * aDiscriptionDict = [NSMutableDictionary dictionary];
    [aDiscriptionDict setObject:@(self.receivedFileSizeInBytes) forKey:@"receivedFileSizeInBytes"];
    [aDiscriptionDict setObject:@(self.expectedFileSizeInBytes) forKey:@"expectedFileSizeInBytes"];
    [aDiscriptionDict setObject:@(self.resumedFileSizeInBytes) forKey:@"resumedFileSizeInBytes"];
    [aDiscriptionDict setObject:self.downloadToken forKey:@"downloadToken"];
    [aDiscriptionDict setObject:self.progress forKey:@"progress"];
    [aDiscriptionDict setObject:@(YES) forKey:@"hasSessionDownloadTask"];
    
    NSString * aDescriptionString = [NSString stringWithFormat:@"%@",aDiscriptionDict];
    return aDescriptionString;
}

@end
